package com.swt.draw.controller;

import com.swt.draw.dao.AdminMapper;
import com.swt.draw.entity.Admin;
import com.swt.draw.example.AdminExample;
import com.swt.draw.vo.BaseResponse;
import com.swt.draw.vo.FileUploadRespVO;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * @ClassName
 * @Description TODO
 * @Author Administrator
 * @Date 2019/9/2 0002 23:30
 * @Version 1.0
 **/
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${headImgs.path}")
    private String filePathRoot;

    @Resource
    private AdminMapper adminMapper;

    /**
     * @Author ZPF
     * @Description 用户上传头像
     * @Date 23:31 2019/9/2 0002
     * @Param []
     * @return com.swt.draw.vo.BaseResponse
     **/
    @PostMapping("/uploadHeadImg")
    public FileUploadRespVO uploadHeadImg(MultipartFile file) throws IOException {
        FileUploadRespVO response = new FileUploadRespVO();
        if(file == null || file.isEmpty()){
            return response;
        }
        Admin admin = (Admin) SecurityUtils.getSubject().getPrincipal();
        String originFileName = file.getOriginalFilename();
        String fileType = originFileName.substring(originFileName.lastIndexOf("."));
        String filePath = new StringBuffer(filePathRoot).append(admin.getAdminNo()).append(fileType).toString();
        File saveFile = new File(filePath);
        if(!saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdirs();
            saveFile.createNewFile();
        }
        file.transferTo(saveFile);
        // 更新用户头像路径
        admin.setAdminAvatarurl(filePath);
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andAdminNoEqualTo(admin.getAdminNo());
        adminMapper.updateByExampleSelective(admin, example);
        response.setCode(0);
        response.setMsg("ok");
        FileUploadRespVO.DataBean data = new FileUploadRespVO.DataBean();
        data.setSrc(filePath);
        response.setData(data);
        return response;
    }
}
